import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hong_vpn_new_20240626/hvn_tools/vpn_manager.dart';
import 'package:hong_vpn_new_20240626/utils/utils.dart';

import 'global.dart';
import 'models/base_resp.dart';
import 'models/chat.dart';
import 'models/vpn_list.dart';

class API {
  static reloadVpnList() async {
    Response response = await Global.dio.get(
      "https://hotvpn.top/hotData/getOpenUrl",
      // "https://smartvpn.top/getSmart/getSmartUrl",
    );
    var respModel = BaseRespModel<List<VpnListModel>>.fromMap(
      response.data,
      dataFromMap: (p0) {
        if (p0 is List) {
          return p0.map((e) => VpnListModel.fromMap(e)).toList();
        }
        return [];
      },
    );
    Global.vpns = respModel.result ?? [];
  }

  static Future<ChatModel> chat(List<ChatModel> chats) async {
    var result = await Global.dio.post(
        "https://ai.hotvpn.top/hotWithAI/chatAnswer",
        data: chats.map((e) => e.toMap()).toList());
    var chatModel = BaseRespModel<String>.fromMap(result.data);
    var time = Utils.getCurrentTime();

    return ChatModel(
        role: UserRole.assistant, content: chatModel.result ?? "", time: time);
  }

  /// 下载VPN
  static Future<String> download(VpnListModel model) async {
    if (model.hotUrl.isEmpty) {
      return Future.error("Download url is empty!");
    }
    var path = await model.ovpnFilePath;
    zzLog("message   $path");
    // 判断文件是否存在
    var file = File(path);
    if (file.existsSync()) {
      // 文件存在 不再下载
      return path;
    }
    EasyLoading.show(maskType: EasyLoadingMaskType.black);
    Response response = await Global.dio.download(model.hotUrl, path);
    EasyLoading.dismiss();
    zzLog("fdajlfdjaslfdsa ${response.data}");
    return path;
  }
}
